<template>
  <!-- 报警配置表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      style="min-height: 500px"
      draggable
      @close="closeDialog"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="120"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="报警编号"
                prop="alarmCode"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.alarmCode"
                  placeholder="请输入报警编号"
                  clearable
                />
                <span v-else>{{ formData.alarmCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="报警名称"
                prop="alarmName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.alarmName"
                  placeholder="请输入报警名称"
                  clearable
                />
                <span v-else>{{ formData.alarmName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="设备类型"
                prop="relationId"
                style="width: 100%"
              >
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.relationId"
                  placeholder="请选择设备类型"
                  clearable
                >
                  <el-option
                    v-for="item in equipTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{ name }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="报警等级"
                prop="alarmLevel"
                style="width: 100%"
              >
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.alarmLevel"
                  clearable
                  placeholder="请选择报警等级"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'ScaAlarmLevel'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName(
                    "ScaAlarmLevel",
                    formData.alarmLevel
                  )
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                label="报警内容"
                prop="alarmContent"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.alarmContent"
                  placeholder="请输入报警内容"
                  clearable
                />
                <span v-else>{{ formData.alarmContent }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="启用状态" prop="enabled" style="width: 100%">
                <el-radio-group
                  v-if="!props.isReadonly"
                  v-model="formData.enabled"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
                <span v-else>{{
                  formData.enabled === 1 ? "启用" : "停用"
                }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remarks" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="持续时间(秒)"
                prop="sustainedTime"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.sustainedTime"
                  placeholder="请输入持续时间(秒)"
                  clearable
                />
                <span v-else>{{ formData.sustainedTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="时间间隔(秒)"
                prop="intervalTime"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.intervalTime"
                  placeholder="请输入时间间隔(秒)"
                  clearable
                />
                <span v-else>{{ formData.intervalTime }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <h4 class="mb-[20px] mt-[20px]">报警数据</h4>
          <el-button
            type="success"
            plain
            @click="handleAdd"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增</el-button
          >
        </div>

        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="250"
            border
          >
            <el-table-column label="参数" props="parameterName" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.parameterName'"
                  :rules="rules.sonparameterName"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.parameterName"
                    placeholder="请输入参数"
                    clearable
                  />
                  <span v-else>{{ row.parameterName }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="条件"
              props="conditionValue"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.conditionValue'"
                  :rules="rules.soncondition"
                  label-width="0"
                >
                  <el-select
                    v-if="!props.isReadonly"
                    v-model="row.conditionValue"
                    clearable
                    placeholder="请选择报警条件"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList(
                        'ScaAlarmConditions'
                      )"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <span v-else>{{
                    dictionaryStore.filterDictName(
                      "ScaAlarmConditions",
                      row.conditionValue
                    )
                  }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="报警值" props="alarmValue" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.alarmValue'"
                  :rules="rules.sonalarmValue"
                  label-width="0"
                >
                  <el-input
                    v-if="!props.isReadonly"
                    v-model="row.alarmValue"
                    placeholder="请输入报警值"
                    clearable
                  />
                  <span v-else>{{ row.alarmValue }}</span>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  :disabled="formData.details.length < 2"
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                  ><i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ADMINSCAALARMSETTINGADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  alarmCode: "",
  alarmName: "",
  alarmLevel: "",
  relationId: "",
  relationType: "",
  sustainedTime: "0",
  intervalTime: "0",
  alarmContent: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      version: "",
      alarmId: "",
      alarmCode: "",
      alarmName: "",
      parameterName: "",
      condition: "",
      alarmValue: "",
      calculate: "",
      isEmpty: "",
      enabled: "",
      deleted: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  alarmCode: [{ required: true, message: "请输入报警编号", trigger: "blur" }],
  alarmName: [{ required: true, message: "请输入报警名称", trigger: "blur" }],
  alarmLevel: [
    { required: true, message: "请选择报警等级", trigger: "change" },
  ],
  alarmContent: [
    { required: true, message: "请输入报警内容", trigger: "blur" },
  ],
  relationId: [
    { required: true, message: "请选择设备类型", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonalarmCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonalarmName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  sonparameterName: [
    { required: true, message: "请输入参数", trigger: "blur" },
  ],
  soncondition: [
    { required: true, message: "请选择报警条件", trigger: "change" },
  ],
  sonalarmValue: [{ required: true, message: "请输入报警值", trigger: "blur" }],
  soncalculate: [
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
  ],
  sonremarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sustainedTime: [
    {
      required: true,
      message: "请输入数字",
      trigger: "blur",
      validator: validator,
    },
  ],
  intervalTime: [
    {
      required: true,
      message: "请输入数字",
      trigger: "blur",
      validator: validator,
    },
  ],
});
function validator(rule, value, callback: (a?: any) => {}) {
  if (!value) {
    //先判断空可以过

    callback(new Error("请输入数字"));
  } else {
    if (/(^[0-9]\d*$)/.test(value)) {
      //验证正整数和0的正则
      return true;
    } else {
      callback(new Error("请输入数字"));
    }
  }
}

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  alarmId: "",
  alarmCode: "",
  alarmName: "",
  parameterName: "",
  conditionValue: "",
  alarmValue: "",
  calculate: "",
  isEmpty: "",
  enabled: "",
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.alarmCode = "";
  formData.alarmName = "";
  formData.alarmLevel = "";
  formData.relationId = "";
  formData.relationType = "";
  formData.sustainedTime = "0";
  formData.intervalTime = "0";
  formData.alarmContent = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 报警配置保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/iotadmin/scaalarmsetting/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}
const name = ref("");
async function getdetails() {
  let sondetails = await request({
    url: "/iotadmin/scaalarmsetting/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
  equipTypeList.value?.forEach((item) => {
    if (item.id == formData.relationId) {
      name.value = `${item.equipTypeName}`;
    }
  });
}

// 获取设备类型下拉框
const equipTypeList: any = ref([]);
const getEquipTypeList = async () => {
  const res = await request({
    url: "/iotadmin/scaequiptype/getlist",
    method: "post",
    data: {},
  });
  if (res.code === 200) {
    equipTypeList.value = res.data;
    equipTypeList.value?.map((item) => {
      item.label = `${item.equipTypeName}`;
      item.value = `${item.id}`;
    });
  }
};

onMounted(() => {
  getEquipTypeList();
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
// .formTable {
//   :deep(.el-form-item) {
//     margin-right: 0 !important;
//     margin-bottom: 14px !important;
//   }
// }
// :deep(.el-dialog .el-dialog__body) {
//   overflow-y: auto;
// }
// :deep(.search-container .el-input.el-input--default.el-input--suffix) {
//   // 固定宽度
//   width: 190px !important;
// }
// :deep(.search-container .el-form-item--default .el-form-item__label) {
//   // 固定宽度
//   justify-content: end;
// }

.formTable {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.el-table .el-form-item) {
  padding: 9px 0 0 0 !important;
}
:deep(.el-table) {
  .el-table__body td.el-table__cell {
    padding: 0 !important;
  }
}
:deep(.el-table .el-form-item__error) {
  font-size: 11px !important;
}
</style>
